import { ChangeEvent, FC, memo, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import styles from './index.module.scss'
import EditToolBar from '../EditToolBar'
import { Button, message, Space, Typography } from 'antd'
import { EditOutlined, LeftOutlined, LoadingOutlined } from '@ant-design/icons'
import useGetComponentInfo from '@/hooks/useGetComponentInfo'
import useGetPageInfo from '@/hooks/useGetPageInfo'
import Input from 'antd/es/input/Input'
import { useDispatch } from 'react-redux'
import { changePageTitle } from '@/store/features/pageReducer'
import { updateQuestion } from '@/service/module/question'
import { useKeyPress, useRequest, useDebounceEffect } from 'ahooks'

const { Title } = Typography

//显示和修改标题
const TitleElem: FC = () => {
  const { title } = useGetPageInfo()
  const [editState, setEditState] = useState(false)
  const dispatch = useDispatch()

  function handleChangeTitle(event: ChangeEvent<HTMLInputElement>) {
    const newValue = event.target.value.trim()
    // if (!newValue) return
    dispatch(changePageTitle(newValue))
  }

  if (editState)
    return (
      <Input
        value={title}
        onChange={handleChangeTitle}
        onPressEnter={() => setEditState(false)}
        onBlur={() => setEditState(false)}
      />
    )
  if (!editState)
    return (
      <Space>
        <Title>{title}</Title>
        <Button icon={<EditOutlined />} type="text" onClick={() => setEditState(true)}></Button>
      </Space>
    )
}

//保存按钮
const SaveButton: FC = () => {
  //pageInfo componentList
  const { id = '' } = useParams()
  const { componentList = [] } = useGetComponentInfo()
  const pageInfo = useGetPageInfo()

  //快捷键
  useKeyPress(['ctrl.s', 'meta.s'], (event: KeyboardEvent) => {
    event.preventDefault()
    if (!loading) save()
  })

  const { run: save, loading } = useRequest(
    async () => {
      if (!id) return
      await updateQuestion(id, { ...pageInfo, componentList })
    },
    {
      manual: true,
    }
  )

  //自动保存
  //useDebounceEffect 有useEffect的功能 还有防抖的功能
  useDebounceEffect(
    () => {
      if (!loading) save()
    },
    [pageInfo, componentList],
    {
      wait: 1000,
    }
  )

  return (
    <Button onClick={save} disabled={loading} icon={loading && <LoadingOutlined />}>
      保存
    </Button>
  )
}

//发布按钮
const PublishButton: FC = () => {
  //pageInfo componentList
  const nav = useNavigate()
  const { id = '' } = useParams()
  const { componentList = [] } = useGetComponentInfo()
  const pageInfo = useGetPageInfo()

  const { run: pub, loading } = useRequest(
    async () => {
      if (!id) return
      await updateQuestion(id, { ...pageInfo, componentList, isPublished: true })
    },
    {
      manual: true,
      onSuccess() {
        message.success('发布成功')
        nav('/question/static/' + id)
      },
    }
  )
  return (
    <Button type="primary" onClick={pub} disabled={loading}>
      发布
    </Button>
  )
}

//编辑器头部
const EditHeader = memo(() => {
  const nav = useNavigate()
  return (
    <div className={styles['header-wrapper']}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space>
            <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
              返回
            </Button>
            <TitleElem />
          </Space>
        </div>
        <div className={styles.center}>
          <EditToolBar />
        </div>
        <div className={styles.right}>
          <Space>
            <SaveButton />
            <PublishButton />
          </Space>
        </div>
      </div>
    </div>
  )
})

export default EditHeader
